<!-- 客户档案--子组建（弹出框） -->
<template>
    <div class="modal-wrapper">
        <drag-modal title="客户档案" :visible="visible" @ok="handleOk" :okText="'保存'" @cancel="handleCancel" :width="'900px'" class="client-modal-class">
            <a-form :form="form">

                <a-tabs default-active-key="1">
                    <a-tab-pane key="1" tab="基本信息">
                        <a-row>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="客户名称" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="off" placeholder="请输入客户名称" @blur="ininventoryBlur" @click="inventoryClick" @change="inventoryChange" v-decorator="['crmName',{rules: [{ required: true, message: '请输入单位名称' }],validateTrigger: ['blur']}]"></a-input>
                                    <div class="crm-select-div" v-show="crmSelect">
                                        <ul v-if="crmArray.length > 0">
                                            <li v-for="(key, index) in crmArray" :key="index" @click="partnerClassNameHandler(key.id)">{{ key.crmName }}</li>
                                        </ul>
                                        <div v-else class="crm-select-null">
                                            暂无数据
                                        </div>
                                    </div>
                                    <!-- <a-select allowClear placeholder="请输入客户名称" @change="partnerClassNameHandler" v-decorator="['crmName',{rules: [{required: true, message: '请输入客户名称' },]},]">
                                <a-select-option v-for="(key, index) in crmArray" :key="index" :value="key.id">
                                    {{ key.crmName }}
                                </a-select-option>
                            </a-select> -->
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="客户简称" v-bind="formItemLayout">
                                    <a-input allowClear type="text" max-length="8" autocomplete="off" placeholder="请输入客户简称" v-decorator="['crmSimpleName',{rules: [{ required: true, message: '请输入客户简称' }],validateTrigger: ['blur']}]"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="拼音码" v-bind="formItemLayout">
                                    <a-input allowClear type="text" max-length="8" autocomplete="off" placeholder="请输入拼音码" v-model="ruleFormData.phonetic"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item v-bind="formItemLayout" label="所属行业">
                                    <a-select placeholder="请选择行业属性" @change="industryChange" v-decorator="['industry',{rules: [{ required: false, message: '请选择行业属性' }]}]">
                                        <a-select-option v-for="(item, index) in industryList" :key="index" :value="item.name">{{ item.name }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item v-bind="formItemLayout" label="所属地区">
                                    <a-cascader placeholder="请选择所属地区" @click="areaTree" @change="onAreaChange" :field-names="{label: 'title',value: 'title',children: 'children'}" v-decorator="['areaName']" :options="regions" />
                                    <!-- <a-cascader placeholder="请选择所属地区" @click="areaTree" @change="onAreaChange" :field-names="{label: 'title',value: 'title',children: 'children'}" v-decorator="['areaName',{rules: [{ type: 'array', required: true, message: '请选择所属地区' }]}]" :options="regions" /> -->
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="法定代表" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="off" placeholder="请输法定代表人" v-model="ruleFormData.legalPerson"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="企业规模" v-bind="formItemLayout">
                                    <a-select placeholder="请选择企业规模" v-model="ruleFormData.enterpriseScale">
                                        <a-select-option value="1-49人">1-49人</a-select-option>
                                        <a-select-option value="50-99人">50-99人</a-select-option>
                                        <a-select-option value="100-499人">100-499人</a-select-option>
                                        <a-select-option value="500-999人">500-999人</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="注册资本" v-bind="formItemLayout">
                                    <a-input-number style="height:34px !important;line-height:34px;width:100%;" type="text" autocomplete="off" placeholder="请输入注册资本" v-model.trim="ruleFormData.registerCapital"></a-input-number>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item v-bind="formItemLayout" label="纳税性质">
                                    <a-select placeholder="请选择纳税性质" v-model="ruleFormData.taxNature">
                                        <a-select-option v-for="(item, index) in taxNatureList" :key="index" :value="item">{{ item }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                    <a-tab-pane key="2" tab="财务信息">
                        <a-row>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="统一代码" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="off" placeholder="请输入统一代码" v-model.trim="ruleFormData.companyNumber"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="地址" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="off" placeholder="请输入地址" v-model.trim="ruleFormData.address"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="开户银行" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" placeholder="请输入开户银行" v-model="ruleFormData.openingBank" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="银行账户" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" placeholder="请输入银行账户" v-model="ruleFormData.bankAccount" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="联系人电话" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="off" placeholder="请输入联系人电话" v-model="ruleFormData.phone"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="电子发票接收邮件" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" placeholder="请输入电子发票接收邮件" v-model.trim="ruleFormData.electronicInvoiceEmail" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="电子发票接收手机" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" placeholder="请输入电子发票接收手机" v-model.trim="ruleFormData.electronicInvoicePhone" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" class="item-col">
                                <a-form-item label="备注" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model.trim="ruleFormData.remarks" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                </a-tabs>
            </a-form>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="handleOk" v-if="isShowSaveBtn">保存</a-button>
                    <a-button @click="handleCancel" class="margin-left-10">关闭</a-button>
                </div>
            </template>
        </drag-modal>
    </div>
</template>
<script>
//区域选择
import { treeList } from "@/api/area";
import { areaPageListToTreeForId } from "@/utils/tree";

import { save } from "@/api/erp/customer";

import { list } from "@/api/erp/customer";
import { list as partnerList } from "@/api/erp/partnerClass";
import { industryList, belongsList } from "@/api/industry";//行业
//获取汉子首字母
import PY from "@/utils/pinyinUtil/pinyin"

export default {
    props: {
        isShowSaveBtn: {
            type: Boolean,
            default: () => false,
        }
        // data: {
        //     type: Array,
        //     default: () => [],
        // },
    },
    data () {
        return {
            visible: false,
            partnerType: [],
            //行业信息列表
            industryList: [],

            labelCol: 10,
            wrapperCol: 14,
            //输入框布局
            formItemLayout: {
                labelCol: { span: 10 },
                wrapperCol: { span: 14 },
            },
            areaCode: "",
            ruleFormData: {
                address: "",
                areaCode: 0, // 省市编码
                areaName: "", // 省市名称
                bank: "",    //开户银行
                bankAccount: "", //银行账户
                bankCode: "",    //所属银行编码

                chargeOfficeId: "", // 租户分管部门ID
                chargeOfficeName: "", // 租户分管部门名字
                chargeUserId: "", // 租户分管人员ID
                chargeUserName: "", // 租户分管人员名字


                contactAddress: "", // 往来单位联系人地址
                contactMan: "", // 往来单位联系人

                companyNumber: "", // 往来单位 社会统一代码
                creditGrade: "", // 信用等级
                creditLimit: "", // 信用额度

                crmId: "",   //客户id
                crmName: "", // 客户名称
                customerAbbName: "", //(废除) 
                crmSimpleName: "",    //客户简称
                phonetic: "",        //客户拼音码
                customerCode: "",    //客户编码
                industry: "",// 行业性质
                partnerClassId: "", //分类
                partnerClassName: "",//分类名

                electronicInvoiceEmail: "",//电子发票接收邮件
                electronicInvoicePhone: "",//电子发票接收手机
                legalPerson: "", // 法人代表
                phone: "", //电话
                riskLevel: "", // 风险等级
                taxNature: "", // 纳税性质(一般纳税人/小规模税人)
                taxRate: "", // 税率

                enterpriseScale: "",//企业规模
                registerCapital: "",//注册资金
            },
            regNum: /^[0-9]*$/,  //纯数字
            regLetter: /^[a-zA-Z\d]+$/,//数字和字母
            regEmail: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,//邮件验证
            regPhone: /^1(3[0-9]|5[189]|8[6789])[0-9]{8}$/, //手机号验证
            //行政区信息
            regions: [],

            //信用等级
            creditRatingArray: [
                {
                    leave: 1,
                    name: "A级",
                },
                {
                    leave: 2,
                    name: "B级",
                },
                {
                    leave: 3,
                    name: "C级",
                },
                {
                    leave: 4,
                    name: "D级",
                },
            ],
            //风险等级
            riskArray: [
                {
                    leave: 1,
                    name: "高",
                },
                {
                    leave: 2,
                    name: "中",
                },
                {
                    leave: 3,
                    name: "低",
                },
            ],
            //纳税性质
            taxNatureList: ["一般纳税人", "小规模税人"],
            //报税地区列表
            taxAreaList: [],
            //是否是零售客户
            retailArray: ["是", "否"],
            crmArray: [],
            crmSelect: false,
        };
    },
    beforeCreate () {
        this.form = this.$form.createForm(this, { name: "name" });
    },
    created () {
        this.areaTree();
        this.ListIndustry();    //行业
        // this.getCustomerType();//分类
        this.getCrmArray();
    },
    methods: {
        showModal () {
            this.visible = true;
        },
        handleCancel () {
            this.visible = false;
        },
        handleAdd () {
            //新增
            this.showModal();
            let { ruleFormData } = this;

            for (const key in ruleFormData) {
                ruleFormData[key] = '';
            }
            this.ruleFormData = ruleFormData;
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        // partnerClassId: this.$form.createFormField({
                        //     value: "",
                        // }),
                        crmName: this.$form.createFormField({
                            value: "",
                        }),
                        crmSimpleName: this.$form.createFormField({
                            value: "",
                        }),
                        areaName: this.$form.createFormField({
                            value: "",
                        }),
                        industry: this.$form.createFormField({
                            value: "",
                        }),
                    };
                },
            });
        },
        handleEdit (row, index) {
            //修改数据
            this.showModal();
            this.$nextTick(() => {
                this.ruleFormData = row;
                if (row) {
                    this.form.setFieldsValue({
                        areaName: row.areaName.split("/"),
                        // partnerClassId: row.partnerClassId,
                        crmName: row.crmName,
                        crmSimpleName: row.crmSimpleName,
                        industry: row.industry,
                    });
                    row.createDate = '';
                    if (row.creditGrade) {
                        row.creditGrade = row.creditGrade == 1 ? "A级" : row.creditGrade == 2 ? "B级" : row.creditGrade == 3 ? "C级" : "D级"; // 信用等级
                    }
                    // if (row.riskLevel) {
                    //     row.riskLevel = row.riskLevel == 1 ? "高" : row.riskLevel == 2 ? "中" : "低"; // 风险等级
                    // }
                }
            });
        },
        handleOk (e) {
            //提交数据
            e.preventDefault();
            this.form.validateFields((err, values) => {
                //所属区域
                let area = "";
                for (let i = 0; i < values.areaName.length; i++) {
                    if (values.areaName.length - i != 1) {
                        area += values.areaName[i] + "/";
                    } else {
                        area += values.areaName[i];
                    }
                }
                values.areaName = area;
                values.areaId = this.areaCode;

                // this.ruleFormData.creditGrade = this.ruleFormData.creditGrade;
                // this.ruleFormData.riskLevel = this.ruleFormData.riskLevel;


                this.ruleFormData = Object.assign(this.ruleFormData, { ...values });

                //信用额度
                let creditLimit = this.ruleFormData.creditLimit;
                if (creditLimit != null && creditLimit != '') {
                    if (!this.regNum.test(creditLimit)) {
                        this.$message.warning('信用额度有误，只能输入正数!');
                        return;
                    }
                }

                //社会统一代码
                let company = this.ruleFormData.companyNumber;
                if (company != null && company != '') {
                    if (!this.regLetter.test(company)) {
                        this.$message.warning('社会统一代码输入有误');
                        return;
                    }
                }

                //邮箱
                let email = this.ruleFormData.electronicInvoiceEmail;
                if (email != null && email != '') {
                    if (!this.regEmail.test(email)) {
                        this.$message.warning('电子发票接收邮件输入有误');
                        return;
                    }
                }

                //手机号  
                let phone = this.ruleFormData.electronicInvoicePhone;
                if (phone != null && phone != '') {
                    if (!this.regPhone.test(phone)) {
                        this.$message.warning('电子发票接收手机输入有误');
                        return;
                    }
                }

                //简称，首拼码
                // this.ruleFormData.phonetic = this.ruleFormData.crmSimpleName;

                console.log("保存的数据：", this.ruleFormData);
                if (!err) {
                    save(this.ruleFormData).then((response) => {
                        if (response.code === 200) {
                            this.$message.success("保存成功");
                            this.handleCancel(); //关闭弹窗
                            this.getCrmArray(); //刷新已经使用的客户
                            this.$emit("ok");
                        } else {
                        }
                    });
                }
            });
        },
        //加载 区域数据
        areaTree () {
            treeList()
                .then((response) => {
                    if (response.code === 200) {
                        const { data } = response;
                        const childrenNav = [];
                        const province = data.filter((f) => f.parentCode == 0);
                        this.taxAreaList = province;
                        areaPageListToTreeForId(data, childrenNav, 0);
                        console.log("加载 区域数据:", childrenNav);
                        this.regions = childrenNav;
                    }
                })
                .catch((error) => { });
        },
        //地区选择事件
        onAreaChange (value, selectedOptions) {
            this.areaCode = selectedOptions.map((o) => o.areaCode)[
                selectedOptions.length - 1
            ];
            // console.log(this.areaText,value,selectedOptions)
        },
        getCustomerType () {
            //获取客户分类
            let params = {
                current: 1,
                size: 500,
                type: 1,
            };
            partnerList(params).then((res) => {
                if (res.code == 200) {
                    this.partnerClass = res.data.records;
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        //加载所属行业
        ListIndustry () {
            belongsList().then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.industryList = data;
                }
            })
                .catch(error => { });
        },
        //选择行业性质：
        industryChange (value) {
            console.log("选择行业性质：", value);
        },
        //客户未使用数组
        partnerClassNameHandler (v, n) {
            console.log(v, n)
            let row = {};
            this.crmArray.forEach(e => {
                if (e.id == v) {
                    row = e;
                }
            });
            console.log(row);
            this.$nextTick(() => {
                this.ruleFormData = row;
                if (row) {
                    this.form.setFieldsValue({
                        areaName: row.areaName != null ? row.areaName.split("/") : '',
                        // partnerClassId: row.partnerClassId,
                        crmName: row.crmName,
                        industry: row.industry,
                    });
                    row.createDate = '';
                    this.inventoryChange({ target: { value: row.crmName } })
                    if (row.creditGrade) {
                        row.creditGrade = row.creditGrade == 1 ? "A级" : row.creditGrade == 2 ? "B级" : row.creditGrade == 3 ? "C级" : "D级"; // 信用等级
                    }
                }
                this.crmSelect = false;
            });

        },
        inventoryChange (val) {
            //物料名称更改
            console.log(val.target.value);
            let pytext = PY.firstPY(val.target.value.trim());
            let reg = new RegExp("gs|zq|kjgs", "g");
            let bb = pytext.replace(reg, "");
            this.ruleFormData.phonetic = bb.slice(0, 8);
            this.getCrmArray(val.target.value);
        },
        inventoryClick () {
            this.crmSelect = true;
            this.getCrmArray();
        },
        ininventoryBlur () {
            setTimeout(() => {
                this.crmSelect = false;
            }, 300)
        },
        getCrmArray (n) {
            //获取客户下拉列表
            let params = {
                current: 1,
                size: 500,
                isFinance: 0,
                name: n
            };
            list(params).then((res) => {
                if (res.code == 200) {
                    this.crmArray = res.data.records;
                    console.log(this.crmArray);
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
    },
};
</script>
<style lang="less">
    .input-box {
        .input-title {
            line-height: 32px;
            text-align: right;
            padding-right: 10px;
        }
        .ant-select {
            width: 100%;
        }
        .input-title::after {
            content: ' :';
        }
        .ant-col {
            margin-bottom: 10px;
        }
    }
    .modal-wrapper .ant-form-item-with-help {
        margin-bottom: 0 !important;
    }
    .ant-input-number-handler-wrap {
        display: none;
    }
    .item-col {
        height: 65px;
    }
    .crm-select-div {
        width: 220px;
        max-height: 160px;
        overflow-y: auto;
        position: absolute;
        background: #fff;
        border: 1px solid #ccc;
        border-top: 0;
        top: 26px;
        z-index: 10;
        box-shadow: 1px 2px 1px rgb(225, 221, 222);
        ul {
            padding: 0;
            margin: 0;
        }
        ul > li {
            list-style: none;
            line-height: 36px;
            padding-left: 10px;
        }
        ul > li:hover {
            background: rgba(200, 200, 201, 1);
        }
        .crm-select-null {
            text-align: center;
            line-height: 72px;
        }
    }
    .client-modal-class {
        .ant-modal-body:first-child {
            height: 510px !important;
            overflow-y: auto !important;
        }
        .item-col {
            height: auto;
        }
        .ant-form-item {
            margin-bottom: 2px;
        }
    }
</style>